991C - Candies - CodeForces Solution


binary search implementation *1500

Please click on ads to support us..

Python Code:

def solveDQ(state, base_cases, get_sub_problems, merge):
  for condition, result in base_cases:
    if condition(state):
      return result(state)
  
  sub_problems = get_sub_problems(state)

  sub_results = [
    solveDQ(sub_problem, base_cases, get_sub_problems, merge) 
    for sub_problem in sub_problems
  ]

  result = merge(sub_results)

  return result

def binary_search_first_high(l, r, condition):
  def get_sub_problems(state):
        l, r = state
    mid = (l + r) // 2
    if condition(mid):
      return [(l, mid)]
    else:
      return [(mid + 1, r)]

  state = (l, r)
  base_cases = [(lambda s: s[0] == s[1], lambda s: s[0])]
  merge = lambda sub_results: sub_results[0]
  return solveDQ(
    state,
    base_cases,
    get_sub_problems,
    merge,
  )

if __name__ == "__main__":
  n = int(input())

  def isValid(n):
    def condition(mid):
      taken = 0
      nonlocal n
      base = n
      while(base):
        portion = base if base <= mid else mid
        taken += portion
        base -= portion
        base -= base // 10
      return 2 * taken >= n
    return condition

  print(binary_search_first_high(1, n, isValid(n)))

C++ Code:

#include <bits/stdc++.h>

#define F first
#define S second
#define endl "\n";
#define shekoo ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);

using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;

const ll mod = 1e9+7;

bool check(ll mid, ll cur){
    ll sum = 0;
    ll n = cur;
    while(cur > 0){
        ll have = min(cur, mid);
        cur -= have;
        sum += have;
        cur -= (cur/10);
    }
    return (2*sum >= n);
}

int main() {
    shekoo
    ll n; cin >> n;
    ll st = 1, en = n, ans = 0;
    while(st <= en){
        ll mid = (st+en)/2;
        if(check(mid, n)){
            ans = mid;
            en = mid-1;
        }
        else{
            st = mid+1;
        }
    }
    cout << ans;
    return 0;
}


Comments

Submit
0 Comments
More Questions

903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS
378A - Playing with Dice
248B - Chilly Willy
1709B - Also Try Minecraft
1418A - Buying Torches
131C - The World is a Theatre
1696A - NIT orz
1178D - Prime Graph
1711D - Rain
534A - Exam
1472A - Cards for Friends
315A - Sereja and Bottles
1697C - awoo's Favorite Problem
165A - Supercentral Point
1493A - Anti-knapsack
1493B - Planet Lapituletti
747B - Mammoth's Genome Decoding
1591C - Minimize Distance
1182B - Plus from Picture
1674B - Dictionary
1426C - Increase and Copy
520C - DNA Alignment